<template>
  <page-header-wrapper>
    <a-card>
      <div class="table-page-search-wrapper">
        <a-form layout="inline" class="table-head-ground">
          <div class="table-layer">
            <a-form-item
              label=""
              class="table-head-layout"
              style="max-width: 350px; min-width: 300px"
            >
              <a-range-picker
                @change="onChange"
                :show-time="{ format: 'HH:mm:ss' }"
                format="YYYY-MM-DD HH:mm:ss"
                :disabled-date="disabledDate"
                :default-value="[
                  moment().subtract(7, 'days'),
                  moment().endOf('day'),
                ]"
              >
                <template v-slot:suffixIcon>
                  <a-icon type="sync" />
                </template>
              </a-range-picker>
            </a-form-item>
            <jeepay-text-up
              :placeholder="'支付订单号'"
              :msg="searchData.payOrderId"
              v-model:value="searchData.payOrderId"
            />
            <jeepay-text-up
              :placeholder="'商户订单号'"
              :msg="searchData.mchOrderNo"
              v-model:value="searchData.mchOrderNo"
            />
            <jeepay-text-up
              :placeholder="'应用AppId'"
              :msg="searchData.appId"
              v-model:value="searchData.appId"
            />
            <a-form-item
              class="table-head-layout"
              style="max-width: 350px; min-width: 300px"
            >
              <a-select v-model:value="searchData.state" placeholder="支付状态">
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="0">订单生成</a-select-option>
                <a-select-option value="1">支付中</a-select-option>
                <a-select-option value="2">支付成功</a-select-option>
                <a-select-option value="3">支付失败</a-select-option>
              </a-select>
            </a-form-item>
            <span class="table-page-search-submitButtons">
              <a-button
                type="primary"
                icon="search"
                @click="queryFunc"
                :loading="btnLoading"
              >搜索</a-button
              >
              <a-button
                style="margin-left: 8px"
                type="primary"
                icon="export"
                @click="handleFile"
                :loading="btnLoading"
              >导出</a-button
              >
              <a-button
                style="margin-left: 8px"
                icon="reload"
                @click="() => (this.searchData = {})"
              >重置</a-button
              >
            </span>
          </div>
          <p v-show="dateObj">
            <span class="data-margin">{{
              `提交订单数:[${dateObj ? dateObj.totalCount : ''}]`
            }}</span>
            <span class="data-margin">{{
              `订单总金额:[${dateObj ? dateObj.totalAmount : ''}]`
            }}</span>
            <span class="data-margin">{{
              `手续费总额:[${dateObj ? dateObj.feeTotalAmount : ''}]`
            }}</span>
            <!-- <span>单笔手续费总额:[] &nbsp;&nbsp;</span> -->
            <span class="data-margin">{{
              `已付总金额:[${dateObj ? dateObj.payTotalAmount : ''}]`
            }}</span>
            <span class="data-margin">{{
              `已付订单数:[${dateObj ? dateObj.payOrderCount : ''}]笔`
            }}</span>
            <span class="data-margin">{{
              `未付总金额:[${dateObj ? dateObj.unpayTotalAmount : ''}]`
            }}</span>
            <span class="data-margin">{{
              `未付订单数: [${dateObj ? dateObj.unpayOrderCount : ''}]笔`
            }}</span>
            <span class="data-margin">{{
              `商户收入:[${dateObj ? dateObj.payTotalAmountTo : ''}]`
            }}</span>
          </p>
        </a-form>
      </div>

      <!-- 列表渲染 -->
      <JeepayTable
        @btnLoadClose="btnLoading = false"
        ref="infoTable"
        :initData="true"
        :reqTableDataFunc="reqTableDataFunc"
        :tableColumns="tableColumns"
        :searchData="searchData"
        rowKey="payOrderId"
        :tableRowCrossColor="true"
      >
        <template v-slot:amountSlot="{ record }">{{
          (record / 100).toFixed(2)
        }}</template>
        <!-- 自定义插槽 -->
        <template v-slot:amountToSlot="{ record }">{{
          (record / 100).toFixed(2)
        }}</template>
        <!-- 自定义插槽 -->
        <template v-slot:stateSlot="{ record }">
          <a-tag
            :key="record.state"
            :color="
              record.state === 0
                ? 'blue'
                : record.state === 1
                  ? 'orange'
                  : record.state === 2
                    ? 'green'
                    : record.state === 6
                      ? ''
                      : 'volcano'
            "
          >
            {{
              record.state === 0
                ? '订单生成'
                : record.state === 1
                  ? '支付中'
                  : record.state === 2
                    ? '支付成功'
                    : record.state === 3
                      ? '支付失败'
                      : record.state === 4
                        ? '已撤销'
                        : record.state === 5
                          ? '已退款'
                          : record.state === 6
                            ? '订单关闭'
                            : '未知'
            }}
          </a-tag>
        </template>
        <template v-slot:orderSlot="{ record }">
          <div class="order-list">
            <p>
              <span style="color: #729ed5; background: #e7f5f7">支付</span
              >{{ record.payOrderId }}
            </p>
            <p style="margin-bottom: 0">
              <span style="color: #56cf56; background: #d8eadf">商户</span>
              <a-tooltip
                placement="bottom"
                style="font-weight: normal"
                v-if="record.mchOrderNo.length > record.payOrderId.length"
              >
                <template v-slot:title>
                  <span>{{ record.mchOrderNo }}</span>
                </template>
                {{
                  changeStr2ellipsis(
                    record.mchOrderNo,
                    record.payOrderId.length
                  )
                }}
              </a-tooltip>
              <span style="font-weight: normal" v-else>{{
                record.mchOrderNo
              }}</span>
            </p>
          </div>
        </template>
        <template v-slot:opSlot="{ record }">
          <!-- 操作列插槽 -->
          <JeepayTableColumns>
            <a-button
              type="link"
              v-if="$access('ENT_PAY_ORDER_VIEW')"
              @click="detailFunc(record.payOrderId)"
            >详情</a-button
            >
          </JeepayTableColumns>
        </template>
      </JeepayTable>
    </a-card>
    <!-- 退款弹出框 -->
    <refund-modal
      ref="refundModalInfo"
      :callbackFunc="searchFunc"
    ></refund-modal>
    <!-- 日志详情抽屉 -->
    <template>
      <a-drawer
        width="50%"
        placement="right"
        :closable="true"
        :visible="visible"
        :title="visible === true ? '订单详情' : ''"
        @close="onClose"
      >
        <a-row justify="space-between" type="flex">
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="支付订单号">
                <a-tag color="purple">
                  {{ detailData.payOrderId }}
                </a-tag>
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="商户号">
                {{ detailData.mchNo }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="商户订单号">
                {{ detailData.mchOrderNo }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="商户名称">
                {{ detailData.mchName }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="应用APPID">
                {{ detailData.appId }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="订单状态">
                <a-tag
                  :color="
                    detailData.state === 0
                      ? 'blue'
                      : detailData.state === 1
                        ? 'orange'
                        : detailData.state === 2
                          ? 'green'
                          : detailData.state === 6
                            ? ''
                            : 'volcano'
                  "
                >
                  {{
                    detailData.state === 0
                      ? '订单生成'
                      : detailData.state === 1
                        ? '支付中'
                        : detailData.state === 2
                          ? '支付成功'
                          : detailData.state === 3
                            ? '支付失败'
                            : detailData.state === 4
                              ? '已撤销'
                              : detailData.state === 5
                                ? '已退款'
                                : detailData.state === 6
                                  ? '订单关闭'
                                  : '未知'
                  }}
                </a-tag>
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="支付金额">
                <a-tag color="green">
                  {{ detailData.amount / 100 }}
                </a-tag>
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions
            ><a-descriptions-item
              label="手续费"
            ><a-tag color="pink">{{
              detailData.mchFeeAmount / 100
            }}</a-tag></a-descriptions-item
            ></a-descriptions
            >
          </a-col>
          <a-col :sm="12">
            <a-descriptions
            ><a-descriptions-item
              label="商家费率"
            >{{
              (detailData.mchFeeRate * 100).toFixed(2)
            }}%</a-descriptions-item
            ></a-descriptions
            >
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="支付错误码">
                {{ detailData.errCode }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="支付错误描述">
                {{ detailData.errMsg }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="订单失效时间">
                {{ detailData.expiredTime }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="支付成功时间">
                {{ detailData.successTime }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="创建时间">
                {{ detailData.createdAt }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="更新时间">
                {{ detailData.updatedAt }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-divider />
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="货币代码">
                {{ detailData.currency }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="客户端IP">
                {{ detailData.clientIp }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="用户标识">
                {{ detailData.channelUser }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="渠道订单号">
                {{ detailData.channelOrderNo }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="异步通知地址">
                {{ detailData.notifyUrl }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="页面跳转地址">
                {{ detailData.returnUrl }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="客户名称">
                {{ detailData.customerName }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="客户手机号">
                {{ detailData.customerPhone }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="客户邮箱">
                {{ detailData.customerEmail }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
        </a-row>
        <a-divider />
        <a-row justify="start" type="flex">
          <a-col :sm="24">
            <a-form-model-item label="渠道额外参数">
              <a-input
                type="textarea"
                disabled="disabled"
                style="height: 100px; color: black"
                v-model:value="detailData.channelExtra"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row justify="start" type="flex">
          <a-col :sm="24">
            <a-form-model-item label="扩展参数">
              <a-input
                type="textarea"
                disabled="disabled"
                style="height: 100px; color: black"
                v-model:value="detailData.extParam"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-drawer>
    </template>
  </page-header-wrapper>
</template>

<script>
import JeepayTextUp from '@/components/JeepayTextUp/JeepayTextUp' // 文字上移组件
import JeepayTable from '@/components/JeepayTable/JeepayTable'
import JeepayTableColumns from '@/components/JeepayTable/JeepayTableColumns'
import RefundModal from './RefundModal' // 退款弹出框
import {
  API_URL_PAY_ORDER_LIST,
  API_URL_PAYWAYS_LIST,
  req,
  handleFileApi,
  API_URL_PAY
} from '@/api/manage'
import moment from 'moment'
import { download } from '@/utils/util'

// eslint-disable-next-line no-unused-vars
const tableColumns = [
  {
    key: 'orderNo',
    title: '订单号',
    scopedSlots: { customRender: 'orderSlot' },
    width: '260px',
    fixed: 'left'
  },
  {
    key: 'amount',
    title: '订单金额',
    dataIndex: 'amount',
    scopedSlots: { customRender: 'amountSlot' },
    fixed: 'left'
  },
  {
    key: 'mchFeeAmount',
    dataIndex: 'mchFeeAmount',
    title: '手续费',
    customRender: (text) => (text / 100).toFixed(2)
  },
  {
    key: 'amountTo',
    title: '商户金额',
    dataIndex: 'amountTo',
    scopedSlots: { customRender: 'amountToSlot' }
  },
  {
    key: 'state',
    title: '支付状态',
    scopedSlots: { customRender: 'stateSlot' }
  },
  {
    key: 'createdAt',
    title: '创建日期',
    dataIndex: 'createdAt',
    width: '220px'
  },
  {
    key: 'op',
    title: '操作',
    width: '120px',
    fixed: 'right',
    align: 'center',
    scopedSlots: { customRender: 'opSlot' }
  }
]

export default {
  name: 'IsvListPage',
  components: { JeepayTable, JeepayTableColumns, JeepayTextUp, RefundModal },
  data () {
    return {
      btnLoading: false,
      tableColumns: tableColumns,
      searchData: {
        createdStart: moment()
          .subtract(7, 'days')
          .format('YYYY-MM-DD HH:mm:ss'),
        createdEnd: moment().format('YYYY-MM-DD HH:mm:ss')
      },
      createdStart: '', // 选择开始时间
      createdEnd: '', // 选择结束时间
      visible: false,
      detailData: {},
      payWayList: [],
      dateObj: null,
      stateList: [
        '全部',
        '订单生成',
        '支付中',
        '支付成功',
        '支付失败',
        '已撤销',
        '已退款',
        '订单关闭'
      ]
    }
  },
  computed: {},
  mounted () {
    if (this.$access('ENT_PAY_ORDER_SEARCH_PAY_WAY')) {
      this.initPayWay()
    }
  },
  methods: {
    getDate (params) {
      req.list(API_URL_PAY, params).then((res) => {
        // 支付方式下拉列表
        this.dateObj = res
      })
    },
    queryFunc () {
      this.btnLoading = true
      this.$refs.infoTable.refTable(true)
    },
    // 请求table接口数据
    reqTableDataFunc (params) {
      this.getDate(params)
      return req.list(API_URL_PAY_ORDER_LIST, params)
    },
    searchFunc: function () {
      // 点击【查询】按钮点击事件
      this.$refs.infoTable.refTable(true)
    },
    // 打开退款弹出框
    openFunc (record, recordId) {
      if (record.refundState === 2) {
        return this.$infoBox.modalError('订单无可退款金额', '')
      }
      this.$refs.refundModalInfo.show(recordId)
    },
    detailFunc: function (recordId) {
      const that = this
      req.getById(API_URL_PAY_ORDER_LIST, recordId).then((res) => {
        that.detailData = res
      })
      this.visible = true
    },
    moment,
    onChange (date, dateString) {
      this.searchData.createdStart = dateString[0] // 开始时间
      this.searchData.createdEnd = dateString[1] // 结束时间
    },
    disabledDate (current) {
      // 今日之后日期不可选
      return current && current > moment().endOf('day')
    },
    onClose () {
      this.visible = false
    },
    initPayWay: function () {
      const that = this
      req.list(API_URL_PAYWAYS_LIST, { pageSize: -1 }).then((res) => {
        // 支付方式下拉列表
        that.payWayList = res.records
      })
    },
    changeStr2ellipsis (orderNo, baseLength) {
      const halfLengh = parseInt(baseLength / 2)
      return (
        orderNo.substring(0, halfLengh - 1) +
        '...' +
        orderNo.substring(orderNo.length - halfLengh, orderNo.length)
      )
    },
    handleFile () {
      let s = {}
      if (this.searchData.state === undefined || this.searchData.state === '') {
        s = {
          createdStart: String(this.searchData.createdStart),
          createdEnd: String(this.searchData.createdEnd)
        }
      } else {
        s = {
          state: String(this.searchData.state),
          createdStart: String(this.searchData.createdStart),
          createdEnd: String(this.searchData.createdEnd)
        }
      }
      handleFileApi(s).then((res) => {
        const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
        const blobUrl = window.URL.createObjectURL(blob)
        download(blobUrl, '支付订单')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.order-list {
  -webkit-text-size-adjust: none;
  font-size: 12px;
  display: flex;
  flex-direction: column;
  p {
    white-space: nowrap;
    span {
      display: inline-block;
      font-weight: 800;
      height: 16px;
      line-height: 16px;
      width: 35px;
      border-radius: 5px;
      text-align: center;
      margin-right: 2px;
    }
  }
}
</style>
